package com.example.tosco;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class ConfigDAO {
	private SQLiteDatabase db;
	private Helper helper;
	private String[] columns = {"_id", "codigo", "nome"};
	
	public ConfigDAO(Context context)
	{
		helper = new Helper(context);
	}
	
	public void open() throws SQLException
	{
		db = helper.getWritableDatabase();
	}
	
	public void close()
	{
		db.close();
	}

	public Config addConfig(Config c)
	{
		ContentValues values = new ContentValues();
		values.put("codigo", c.getCodigo());
		values.put("nome", c.getNome());
		
		long insertId = db.insert("Config", null, values);
		Cursor cursor = db.query("Config", columns, "_id = " + insertId, null, null, null, null);
		
		cursor.moveToFirst();
		Config newConfig= cursorToConfig(cursor);
		cursor.close();
		
		return newConfig;
	}

	public void update(Config c){
		ContentValues values = new ContentValues();
		values.put("codigo", c.getCodigo());
		values.put("nome", c.getNome());

		long updateId = db.update("Config", values, "_id=" + c.getCodigo(), null);
		
	}
	
	public Config busca(int codigo){
		Cursor cursor = db.query("Config", columns, "_id = " + codigo, null, null, null, null);
		
		cursor.moveToFirst();
		Config c= cursorToConfig(cursor);
		cursor.close();
		
		return c;
	}
	
	public List<Config> getLista()
	{
		List<Config> Config = new ArrayList<Config>();
		
		Cursor cursor = db.query("Config", columns, null, null, null, null, null);
		
		cursor.moveToFirst();
		while(!cursor.isAfterLast())
		{
			Config.add(cursorToConfig(cursor));
			cursor.moveToNext();
		}
		
		cursor.close();
		return Config;
	}
	
	private Config cursorToConfig(Cursor cursor)
	{
		Config config = new Config();
		
		config.setId(cursor.getLong(0));
		config.setCodigo(cursor.getLong(1));
		config.setNome(cursor.getString(2));
		
		return config;
	}
}
